# Copyright (c) 2018 Presto Labs Pte. Ltd.
# Author: yuxuan

from coin.database.builder.archive_feed_cache_builder import ArchiveFeedCacheBuilder
from coin.strategy.mm.subscription import (
    get_subscription_key,
    SubscriptionRequest,
)
from coin.support.feed_tool.feed_stats.logic.util import to_book_builder_exchange_symbol


class OkexArchiveFeedCacheBuilder(ArchiveFeedCacheBuilder):
  _sub_request = SubscriptionRequest('Futures', 'Okex', None)

  def __init__(self, products, columns, interval_ends):
    ArchiveFeedCacheBuilder.__init__(self, products, columns, interval_ends)

  @staticmethod
  def exchange():
    return 'Okex'

  def on_book_reset(self, book_builder_name, book_builder):
    for product in self._products:
      if book_builder_name == get_subscription_key(product):
        book_builder.subscribe_ticker(product, self.on_feed)

  def _get_value(self, data, column):
    if column == 'open_interest':
      return data.open_interest
    else:
      raise ValueError('Unknown field for Okex ticker %s' % column)

  def on_feed(self, ticker):
    map_data = {column: self._get_value(ticker, column) for column in self._columns}
    self.on_feed_impl(ticker.timestamp, ticker.product, map_data)
